//
//  ST_PairsCenterMatchPecCell.swift
//  btvideo
//
//  Created by mac on 2020/9/4.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyAttributes
import HandyJSON

// 对方与自己有匹配度时
class ST_PairsCenterMatchPecCell: UITableViewCell {
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
    
        contentView.backgroundColor = UIColor.init(hex: 0xACB4C0)
        
        contentView.addSubview(corner_radius_view)
        corner_radius_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 3, left: 0, bottom: 0, right: 0))
        }
        
        corner_radius_view.addSubview(matchValueImageView)
        matchValueImageView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(173)
        }
        
        
        contentView.addSubview(heart_image_view)
        heart_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.height.equalTo(58)
            make.top.equalToSuperview().offset(15)
        }
        
        contentView.addSubview(value_label)
        value_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
            make.top.equalToSuperview().offset(83)
        }
        
        contentView.addSubview(leftAvatarImageView)
        contentView.addSubview(rightAvatarImageView)
        
        rightAvatarImageView.snp.makeConstraints { (make) in
            make.right.equalTo(heart_image_view.snp.left).offset(-15)
            make.width.height.equalTo(40)
            make.top.equalTo(value_label.snp.bottom).offset(15)
        }
        
        leftAvatarImageView.snp.makeConstraints { (make) in
            make.right.equalTo(rightAvatarImageView.snp.left).offset(10)
            make.width.height.equalTo(40)
            make.top.equalTo(value_label.snp.bottom).offset(15)
        }
        
        
        contentView.addSubview(match_value_label)
        match_value_label.snp.makeConstraints { (make) in
            make.centerY.equalTo(leftAvatarImageView)
            make.left.equalTo(rightAvatarImageView.snp.right).offset(10)
        }
        
        contentView.addSubview(myLikeItemView)
        contentView.addSubview(likeMeItemView)
        
        myLikeItemView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(matchValueImageView.snp.bottom)
            make.height.equalTo(100)
        }
        
        likeMeItemView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(myLikeItemView.snp.bottom)
            make.height.equalTo(100)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var value_label:UILabel = {
       let control = UILabel()
        return control
    }()
    
    fileprivate lazy var match_value_label:UILabel = {
       let control = UILabel()
        return control
    }()
    
    fileprivate lazy var leftAvatarImageView:UIImageView = {
       let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 20
        control.borderColor = .white
        control.borderWidth = 1
        return control
    }()
    
    fileprivate lazy var rightAvatarImageView:UIImageView = {
       let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 20
        control.borderColor = .white
        control.borderWidth = 1
        return control
    }()
    
    
    fileprivate lazy var heart_image_view:UIImageView = {
       let control = UIImageView()
        control.image = ST_ImageUtils.imageName("peculiarity_value_heart_icon")
        return control
    }()
    
    fileprivate lazy var corner_radius_view:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        control.cornerRadius = 30
        return control
    }()
    
    fileprivate lazy var matchValueImageView:UIImageView = {
       let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.image = ST_ImageUtils.imageName("peculiarity_match_value_icon")
        control.clipsToBounds = true
        return control
    }()
    
    
    fileprivate lazy var myLikeItemView:PairsCenterPeculiaritySectionView = {
       let control = PairsCenterPeculiaritySectionView()
        return control
    }()
    
    fileprivate lazy var likeMeItemView:PairsCenterPeculiaritySectionView = {
       let control = PairsCenterPeculiaritySectionView()
        return control
    }()
    
    
    var model:ST_PairsCenterMatchPecCellModel?{
        didSet{
            
            guard let m = model else { return }
            
            
            value_label.attributedText = m.matchNumberStr
            
            match_value_label.attributedText = m.matchPercentStr
            
            
            leftAvatarImageView.pin_setImage(from: m.matchInfo.avatar.compress_small_image(width: 120).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            rightAvatarImageView.pin_setImage(from: m.matchInfo.targetAvatar.compress_small_image(width: 120).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            myLikeItemView.snp.updateConstraints { (make) in
                make.height.equalTo(m.myLoveArrayHeight)
            }
            
            myLikeItemView.model_list = m.myLoveArray
            
            likeMeItemView.snp.updateConstraints { (make) in
                make.height.equalTo(m.loveMeArrayHeight)
            }
            
            likeMeItemView.model_list = m.loveMeArray
            
            likeMeItemView.title = m.genderStr + "喜欢我的特质"
            
            myLikeItemView.title = m.genderStr + "有我喜欢的特质"
        }
    }
    
}


//MARK:- Math Model
class ST_PairsCenterMatchPecCellModel: NSObject,ST_CellTypeProtocol {
    
    var cellType: ST_PairsCenterCellType = .peculiarityMatch
    
    var pairsCellHeight: CGFloat = 100
    
    var myLoveArray:[ST_PairsPeculiarity]
    
    var myLoveArrayHeight = 0.cgFloat
    
    var loveMeArray:[ST_PairsPeculiarity]
    
    var loveMeArrayHeight = 0.cgFloat
    
    var matchInfo:PairsMatchInfo
    
    var genderStr:String
//    ex:你们有4个特质互相匹配
    var matchNumberStr = NSAttributedString()
//    ex:你们的匹配度：95%
    var matchPercentStr = NSAttributedString()
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON,gender:String){
        
        genderStr = gender
        
        myLoveArray = json["target_have_i_like"].arrayValue.map { (itemJson) -> ST_PairsPeculiarity in
            return ST_PairsPeculiarity.deserialize(from: itemJson.rawString() ?? "") ?? ST_PairsPeculiarity()
        }
        
        loveMeArray = json["target_like_i_have"].arrayValue.map { (itemJson) -> ST_PairsPeculiarity in
            return ST_PairsPeculiarity.deserialize(from: itemJson.rawString() ?? "") ?? ST_PairsPeculiarity()
        }
        
        
        matchInfo = PairsMatchInfo.init(fromJson: json["match_info"])
        
        super.init()
        
        
        
//        你们有4个特质互相匹配
        matchNumberStr = "你们有".withAttributes([Attribute.textColor(Color.white),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold))]) + matchInfo.matchCount.string.withAttributes([Attribute.textColor(Color.init(hex: 0xFF1F56)!),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold))]) + "个特质互相匹配".withAttributes([Attribute.textColor(Color.white),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold))])
        
        
        
//        你们的匹配度：95%
        matchPercentStr = "你们的匹配度：".withAttributes([Attribute.textColor(Color.white),Attribute.font(Font.systemFont(ofSize: 16, weight: UIFont.Weight.semibold))]) + (matchInfo.match_rate.string + "%").withAttributes([Attribute.textColor(Color.init(hex: 0xFF1F56)!),Attribute.font(Font.systemFont(ofSize: 16, weight: UIFont.Weight.semibold))])
        
        
        myLoveArrayHeight = PairsCenterPeculiaritySectionView.getHeight(itemCount: myLoveArray.count)
        
        loveMeArrayHeight = PairsCenterPeculiaritySectionView.getHeight(itemCount: loveMeArray.count)
        
         pairsCellHeight = myLoveArrayHeight + loveMeArrayHeight + 25 + 173
        
    }
    
}

class PairsMatchInfo : NSObject{

    var avatar : String
    var matchCount : Int
    var match_rate : Int
    var targetAvatar : String
    var targetHaveILikeCount : Int
    var targetLikeIHaveCount : Int

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        avatar = json["avatar"].stringValue
        matchCount = json["match_count"].intValue
        match_rate = json["match_rate"].intValue
        targetAvatar = json["target_avatar"].stringValue
        targetHaveILikeCount = json["target_have_i_like_count"].intValue
        targetLikeIHaveCount = json["target_like_i_have_count"].intValue
        
        super.init()
    }
}




//MAKR: -
class PairsCenterPeculiaritySectionView: UIView {
    
    
    class func getHeight(itemCount:Int)->CGFloat{
        
        let itemHeight = (ScreenWidth - 30 - 18)/4 + 10 + 12
        
        let row = (itemCount.float / 4.0).ceil - 1
        
        let y = row.cgFloat*(itemHeight+6)
        
        return y + itemHeight + 61
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
//        self.backgroundColor = .random
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(16+20+20)
//            make.width.equalTo(100)
            make.top.equalToSuperview().offset(5)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var itemWidth = (ScreenWidth - 30 - 18)/4
    
    fileprivate lazy var itemHeight = self.itemWidth + 10 + 12
    
    fileprivate lazy var itemGap = 6.cgFloat
    
    fileprivate lazy var titleLabel:UILabel = {
       let control = UILabel()
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    var title = ""{
        didSet{
            titleLabel.text = title
//            titleLabel.backgroundColor = .random
//            print("titleLabel 不见了：",titleLabel)
        }
    }
    
    var model_list = [ST_PairsPeculiarity](){
        didSet{
            
            btnArray.forEach({$0.removeFromSuperview()})
            
            
            for (idx,model) in model_list.enumerated(){
                
                /*{
                 0 -> 0
                 1 -> 0
                 2 -> 0
                 3 -> 0
                 4 -> 1
                 }*/
                let 行 = ((idx.float + 1) / 4.0).ceil - 1
                
                let 列 = idx%4
                
                
                print("行列---行：",行,"----列:",列)
                
                let x = 列.cgFloat*(itemWidth+6) + 15
                
                let y = 行.cgFloat*(itemHeight+6)
                
                let btn = createButton(model: model)
                
                btn.snp.makeConstraints { (make) in
                    make.width.equalTo(itemWidth)
                    make.height.equalTo(itemHeight)
                    make.top.equalTo(titleLabel.snp.bottom).offset(y)
                    make.left.equalToSuperview().offset(x)
                }
                
            }
        }
    }
    
    fileprivate lazy var baseTag = 1777
    
    fileprivate lazy var btnArray = [ST_VerticalButton]()
    
    fileprivate func createButton(model:ST_PairsPeculiarity)->ST_VerticalButton{
        
        let btn = ST_VerticalButton()
        
//        btn.backgroundColor = .random
        
        btn.tag = btnArray.count + baseTag
        
        btnArray.append(btn)
        
        self.addSubview(btn)
        
        let str = model.name.withAttributes([Attribute.font(Font.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),Attribute.textColor(Color.init(hex: 0x333333)!)])
        
        btn.setTitleForAllStates(str)
        
        btn.imageView.cornerRadius = 10
        
        btn.imageView.pin_setImage(from: model.image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        btn.image_view_edges = UIEdgeInsets.init(top: 0, left: 0, bottom: 10+12, right: 0)
        
        btn.title_bottom_offset = 0
        
        btn.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
        
        return btn
    }
    
    
    @objc fileprivate func click(sender:ST_VerticalButton){
        
        guard let currModel = model_list[safe:sender.tag - self.baseTag] else{
            return
        }
        
        var sameGender = true
        //     自己的话 这个地方展示异性特质
        if title.contains("我"){
            sameGender = false
        }else if title.contains("他") && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            sameGender = false
        }else if title.contains("她") && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            sameGender = false
        }
        
        push_peculiarity(id: currModel.id, onlyDisplayPerson: sameGender, navigationController: self.parentViewController?.navigationController)
    }
}
